package net.jlibrary.invoice.action;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import net.jlibrary.common.project.util.HttpClientUtils;
import net.jlibrary.curbparking.service.IParkRecordManager;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo.ElectronicInvoiceGfInfoVo;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo.ElectronicInvoiceGfInfoVo.PlateNumberVo;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo.ElectronicInvoiceVo;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo.InvoiceStatusVo;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo.InvoiceTypeVo;
import net.jlibrary.invoice.action.vo.ElectronicInvoiceKpActionVo.ParkRecordVo;
import net.jlibrary.invoice.domain.ElectronicInvoiceKpInfo;
import net.jlibrary.invoice.domain.req.CreateInvoiceReq;
import net.jlibrary.invoice.domain.req.ElectronicInvoiceReq;
import net.jlibrary.invoice.domain.req.GoodsReq;
import net.jlibrary.invoice.domain.req.NotifyUrlReq;
import net.jlibrary.invoice.domain.resp.CreateInvoiceResp;
import net.jlibrary.invoice.domain.resp.CreateResultObjResp;
import net.jlibrary.invoice.domain.resp.InvoiceDetail;
import net.jlibrary.invoice.domain.resp.NegativeInvoice;
import net.jlibrary.invoice.service.IElectronicInvoiceGfInfoManager;
import net.jlibrary.invoice.service.IElectronicInvoiceKpInfoManager;
import net.jlibrary.invoice.service.IElectronicInvoiceManager;

@RequestMapping("/test")
@RestController()
public class TestInvoiceAction {

	@Autowired
	private IElectronicInvoiceKpInfoManager kpInfoManager;
	@Autowired
	private IElectronicInvoiceGfInfoManager gfInfoManager;
	@Autowired
	private IElectronicInvoiceManager xfInfoManager;
	@Autowired
	private IParkRecordManager recordManager;

	public static String TONKEN_STRING = "";

	public static String testUrlString = "http://www.zsinnovate.com/apiTest";

	// 登录获得token
	// @RequestMapping(value = "/testDemo", method = { RequestMethod.POST })
	public void testDemo() {
		String urlString = testUrlString + "/api/center/system/login";
		JSONObject json = new JSONObject();
		json.put("loginName", "nuo4");
		json.put("password", "123456");
		String jsonString = JSONObject.toJSONString(json);
		String result = HttpClientUtils.doPostFormToJson(urlString, null, jsonString);
		JSONObject jsonobj = JSON.parseObject(result);
		String tokenString = jsonobj.getJSONObject("resultObj").getString("token");
		TONKEN_STRING = tokenString;
		List<Object> list = null;
	}

	// 查询该订单的 销方信息
	@RequestMapping(value = "/testGroup", method = { RequestMethod.GET })
	public JSONObject getElectronicInvoice(Long id, Long parkRecordId) {
		JSONObject invoice = new JSONObject();
		JSONObject json = new JSONObject();
		JSONObject goods = new JSONObject();
		if (id != null) {
			invoice = kpInfoManager.getInvoice(id);// 销方信息
		}
		net.jlibrary.curbparking.action.vo.ParkRecordVo recordVo = new net.jlibrary.curbparking.action.vo.ParkRecordVo();
		if (parkRecordId != null) {
			recordVo.setId(parkRecordId);
			recordVo = recordManager.get(recordVo);
			String recordString = JSON.toJSONString(recordVo);
			json = JSON.parseObject(recordString);
			json.remove("id");
			json.put("orderNo", recordVo.getId());
		}
		JSONObject electronicInvoiceJson = new JSONObject();
		electronicInvoiceJson.putAll(invoice);
		electronicInvoiceJson.putAll(json);
		goods = kpInfoManager.getGoods();
		electronicInvoiceJson.putAll(goods);
		ModelMap map = new ModelMap();
		map.put("success", true);
		return electronicInvoiceJson;
	}

	// 开票接口
	@RequestMapping(value = "/testData", method = { RequestMethod.POST })
	public ModelMap testData(ElectronicInvoiceReq invoiceReq) {
		String code = null;
		String msg = null;
		CreateResultObjResp resultObj = new CreateResultObjResp();
		testDemo();
		// 先调用接口开票,再保存开票信息
		CreateInvoiceReq req = new CreateInvoiceReq();
		try {
			BeanUtils.copyProperties(req, invoiceReq);
			req.setXhdwsbh(invoiceReq.getNsrsbh());
			req.setGhdwdzdh(invoiceReq.getGhdwdz() + " " + invoiceReq.getGhdwdh());
			req.setGhdwyhzh(invoiceReq.getGhdwyhmc() + " " + invoiceReq.getGhdwyh());
			GoodsReq goods = new GoodsReq();
			BeanUtils.copyProperties(goods, invoiceReq);
			goods.setDj(invoiceReq.getMoney());// 单价 暂时为总金额(单个订单开票)
			goods.setJe(invoiceReq.getMoney());
			goods.setSl(Double.parseDouble(invoiceReq.getSlKind().getCode()));// 税率
			ArrayList<GoodsReq> goodsVos = new ArrayList<GoodsReq>();
			goodsVos.add(goods);
			req.setGoodsVos(goodsVos);
			req.setNotifyUrl("http://38w025y952.zicp.vip:50545/curbParking/test/notifyUrl");// 回调地址
			String urlString = testUrlString + "/api/invoice/simpleInvoice/createInvoiceCustom";
			String jsonObject = JSONObject.toJSONString(req);
			String result = HttpClientUtils.doPostFormToJson(urlString, TONKEN_STRING, jsonObject);
			CreateInvoiceResp createInvoiceResp = JSON.parseObject(result, CreateInvoiceResp.class);
			code = createInvoiceResp.getCode();
			msg = createInvoiceResp.getMsg();
			if (!code.equals("0000")) {
				ModelMap map = new ModelMap();
				map.put("success", true);
				map.put("msg", msg);
				return map;
			} else {
				resultObj = createInvoiceResp.getResultObj();
			}
		} catch (IllegalAccessException | InvocationTargetException e) {
			e.printStackTrace();
		}
		ElectronicInvoiceGfInfoVo gfActionVo = new ElectronicInvoiceKpActionVo().new ElectronicInvoiceGfInfoVo();
		if (!StringUtils.isBlank(invoiceReq.getGhdwmc())) {
			gfActionVo.setGhdwmc(invoiceReq.getGhdwmc());
		}
		if (!StringUtils.isBlank(invoiceReq.getGhdwsbh())) {
			gfActionVo.setGhdwsbh(invoiceReq.getGhdwsbh());
		}
		if (!StringUtils.isBlank(invoiceReq.getGhdwdz())) {
			gfActionVo.setGhdwdz(invoiceReq.getGhdwdz());
		}
		if (!StringUtils.isBlank(invoiceReq.getGhdwdh())) {
			gfActionVo.setGhdwdh(invoiceReq.getGhdwdh());
		}
		if (!StringUtils.isBlank(invoiceReq.getGhdwyhmc())) {
			gfActionVo.setGhdwyhmc(invoiceReq.getGhdwyhmc());
		}
		if (!StringUtils.isBlank(invoiceReq.getGhdwdh())) {
			gfActionVo.setGhdwdh(invoiceReq.getGhdwdh());
		}
		if (!StringUtils.isBlank(invoiceReq.getGhdwyh())) {
			gfActionVo.setGhdwyh(invoiceReq.getGhdwyh());
		}
		if (!StringUtils.isBlank(invoiceReq.getGfkhyx())) {
			gfActionVo.setGfkhyx(invoiceReq.getGfkhyx());
		}
		// 创建购方信息表
		PlateNumberVo numberVo = new ElectronicInvoiceKpActionVo().new ElectronicInvoiceGfInfoVo().new PlateNumberVo();
		numberVo.setId(invoiceReq.getPlateNumber().getId());
		gfActionVo.setPlateNumber(numberVo);
		// 购方信息
		gfInfoManager.save(gfActionVo);
		// 销方信息
		ElectronicInvoiceVo invoiceActionVo = new ElectronicInvoiceKpActionVo().new ElectronicInvoiceVo();
		invoiceActionVo.setId(invoiceReq.getInvoiceXfId());
		// 订单信息
		ParkRecordVo recordVo = new ElectronicInvoiceKpActionVo().new ParkRecordVo();
		recordVo.setId(Long.valueOf(invoiceReq.getOrderNo()));
		ElectronicInvoiceKpActionVo actionVo = new ElectronicInvoiceKpActionVo();
		actionVo.setEiSetting(invoiceActionVo);
		actionVo.setGfInfo(gfActionVo);
		actionVo.setRecord(recordVo);
		// 根据code 查询字典中InvoiceType的id
		InvoiceTypeVo invoiceType = new ElectronicInvoiceKpActionVo().new InvoiceTypeVo();
		invoiceType.setId(kpInfoManager.invoiceType(resultObj.getInvoiceType()));
		invoiceType.setCode(resultObj.getInvoiceType());
		actionVo.setInvoiceType(invoiceType);
		// 根据code 查询字典中InvoiceStatus的id
		InvoiceStatusVo invoiceStatus = new ElectronicInvoiceKpActionVo().new InvoiceStatusVo();
		invoiceStatus.setId(kpInfoManager.invoiceStatus(String.valueOf(resultObj.getStatus())));
		actionVo.setStatus(invoiceStatus);
		kpInfoManager.save(actionVo);
		ModelMap map = new ModelMap();
		map.put("success", true);
		map.put("msg", msg);
		map.put("resultObj", resultObj);
		return map;
	}

	// 回调地址 接收异步回调响应
	@RequestMapping(value = "/notifyUrl", method = { RequestMethod.POST })
	public void testAsynResponse(JSONObject jsonObject) {
		System.out.println("3--------------" + jsonObject);
		String jsonString = jsonObject.toString();
		// 开票回调接口
		NotifyUrlReq notifyUrlReq = JSON.parseObject(jsonString, NotifyUrlReq.class);
		ElectronicInvoiceKpInfo info = kpInfoManager.electronicInvoiceKpInfo(notifyUrlReq.getOrderNo());
		kpInfoManager.invoiceKpInfo(info, notifyUrlReq);
	}

	// 查询发票详情 说明:根据商家订单号查询发票详情 通过orderNo 商家订单唯一编号 和 xhdwsbh 销货单位识别号
	@RequestMapping(value = "/testCreateInvoiceDetail", method = { RequestMethod.POST })
	public ModelMap invoiceDetail(String orderNo, String xhdwsbh) {
		testDemo();
		JSONObject req = new JSONObject();
		req.put("orderNo", orderNo);
		req.put("xhdwsbh", xhdwsbh);
		String urlString = testUrlString + "/api/invoice/simpleInvoice/queryInvoiceByOrderNo";
		String jsonObject = JSONObject.toJSONString(req);
		String result = HttpClientUtils.doPostFormToJson(urlString, TONKEN_STRING, jsonObject);
		InvoiceDetail invoice = JSON.parseObject(result, InvoiceDetail.class);
		if (!invoice.getCode().equals("0000")) {
			// 失败的情况下
			ModelMap map = new ModelMap();
			map.put("success", true);
			map.put("msg", invoice.getMsg());
			return map;
		}
		System.out.println("9-----------" + result);
		// 查询orderNo对应的发票信息
		ElectronicInvoiceKpInfo info = kpInfoManager.electronicInvoiceKpInfo(orderNo);
		kpInfoManager.upKpInfo(info, invoice);
		ModelMap map = new ModelMap();
		map.put("msg", invoice.getMsg());
		return map;
	}

	// 红冲发票 接口地址:/api/invoice/simpleInvoice/createNegativeInvoice
	/**
	 * 请求示例： { "fpdm":"011002680026", "fphm":"00286213" }
	 * 
	 * @param jsonObject
	 * @return
	 */
	@RequestMapping(value = "/negativeInvoice", method = RequestMethod.POST)
	public ModelMap createNegativeInvoice(String fpdm, String fphm, String xxbbh) {
		testDemo();
		JSONObject req = new JSONObject();
		req.put("fpdm", fpdm);
		req.put("fphm", fphm);
		req.put("xxbbh", xxbbh);
		String param = JSONObject.toJSONString(req);
		String urlString = testUrlString + "/api/invoice/simpleInvoice/createNegativeInvoice";
		String result = HttpClientUtils.doPostFormToJson(urlString, TONKEN_STRING, param);
		NegativeInvoice invoice = JSON.parseObject(result, NegativeInvoice.class);
		if (!invoice.getCode().equals("0000")) {
			// 失败的情况下
			ModelMap map = new ModelMap();
			map.put("success", true);
			map.put("msg", invoice.getMsg());
			return map;
		}
		// 查询发票代码和发票号码对应的发票信息
		ElectronicInvoiceKpInfo info = kpInfoManager.invoiceKpInfo(fpdm, fphm);
		kpInfoManager.negativeInfo(info, invoice);
		ModelMap map = new ModelMap();
		map.put("msg", invoice.getMsg());
		return map;
	}

}
